package crp.core.security.domain.services;

import com.qwlabs.lang.Emails;
import com.qwlabs.lang.Mobiles;
import crp.core.security.domain.models.UserBasicCredentialEntity;
import crp.core.security.domain.models.UserBasicPrincipalType;
import crp.core.security.domain.repositories.UserBasicCredentialRepository;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Optional;

@ApplicationScoped
public class UserBasicCredentialService {
    private final UserBasicCredentialRepository repository;

    @Inject
    public UserBasicCredentialService(UserBasicCredentialRepository repository) {
        this.repository = repository;
    }

    private UserBasicPrincipalType determineType(String principal) {
        if (Mobiles.isMobile(principal)) {
            return UserBasicPrincipalType.MOBILE;
        }
        if (Emails.isEmail(principal)) {
            return UserBasicPrincipalType.EMAIL;
        }
        return UserBasicPrincipalType.USERNAME;
    }


    public Optional<UserBasicCredentialEntity> getBy(String principal) {
        return repository.findBy(this.determineType(principal), principal);
    }

}
